package com.epfresh.supplier.activity;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.TagPager;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.widget.list.LoadMoreListView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.api.widget.ptr.PtrMdFrameLayout;
import com.epfresh.supplier.R;
import com.epfresh.supplier.adapter.OfferHistoryAdapter;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.supplier.entity.MinusRecordBean;
import com.epfresh.supplier.entity.OfferListEntity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
历史报价
*/

public class OfferHistoryListActivity extends BaseActivity implements LoadMoreListView.IXListViewListener{
    private LoadMoreListView mListView;
    private ArrayList<OfferListEntity.ContentBean.ProductListBean> list;
    Context mContext;
    OfferHistoryAdapter adapter;
    protected View mainView;
    protected View vException;
    protected TextView tvExceptionDescription;
    protected ImageView ivExceptionIcon;
    private ProgressBar pb;
    private int requestSucceedCount = 0;
    private int PAGE_SIZE = 5;
    private TagPager tagPager = new TagPager();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        //list = new ArrayList<MinusRecordBean.ContentBean.ListBean>();
        list = new ArrayList<OfferListEntity.ContentBean.ProductListBean>();

        mListView.setPullLoadEnable(true); // 设置可滑动
        mListView.setXListViewListener(this);// 设置滑动监听器
        mContext = this;
        adapter = new OfferHistoryAdapter(this, list);
        mListView.setAdapter(adapter);
        baseback.setVisibility(View.VISIBLE);
        initHeadView();
        requestOrderList(0);
    }

    void initView(){
        setContentView(R.layout.activity_list_minus);
        mListView = (LoadMoreListView)findViewById(R.id.listview);
        basetitle.setText("历史抢单");
        rightbtn.setOnClickListener(this);
        vException = findViewById(R.id.v_exception);
        mainView = findViewById(R.id.fragment_ptr_home_ptr_frame);
        initException();
    }


    public void initException() {
        tvExceptionDescription = (TextView) vException.findViewById(R.id.tv_exception);
        ivExceptionIcon = (ImageView) vException.findViewById(R.id.iv_exception);
        pb = (ProgressBar) vException.findViewById(R.id.pb);
    }


    public void showMainView() {
        vException.setVisibility(View.GONE);
        mainView.setVisibility(View.VISIBLE);
    }


    public void showExceptionView(int imgSrc, String text, int exceptionType) {
        if (imgSrc > 0) {

        }
        pb.setVisibility(View.GONE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.VISIBLE);
        ivExceptionIcon.setVisibility(View.VISIBLE);
        mainView.setVisibility(View.GONE);

        ivExceptionIcon.setImageResource(imgSrc);
        tvExceptionDescription.setText(text);
        tvExceptionDescription.setTag(exceptionType);
        ivExceptionIcon.setTag(exceptionType);
        tvExceptionDescription.setOnClickListener(this);
        ivExceptionIcon.setOnClickListener(this);
    }
    public void showProgressView() {

        pb.setVisibility(View.VISIBLE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.GONE);
        ivExceptionIcon.setVisibility(View.GONE);
        mainView.setVisibility(View.GONE);
    }


    private PtrMdFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, mListView, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    private void initHeadView() {
        ptrFrameLayout = (PtrMdFrameLayout) findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
    }

    boolean refreshFlag = false;
    public void refresh() {
        mListView.resetNoMore();
        refreshFlag = true;
        requestOrderList(0);
    }

    @Override
    public void onLoadMore() {
        int number = tagPager.getNumber();
        requestOrderList( number + 1);
    }


    public void updateViewStatus(RequestTag requestTag) {
        ptrFrameLayout.refreshComplete();
        if (tagPager.isLast()) {
            mListView.noMore();
        } else {
            mListView.stopLoadMore();
        }
    }

    private RequestTag requestTag = new RequestTag();
    public void requestOrderList(int page) {

        RequestEntitySupply<Map<String, String>> entity = new RequestEntitySupply<>();
        Map<String, String> map = new HashMap<>();
        map.put("storeId", BaseApplication.getInstance().getStoreId());
        map.put("pageNumber", page + "");
        map.put("pageSize", "10");

        entity.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_offer_supplyOfferHisList);
        entity.setParameters(map);
        requestTag.tag = com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_offer_supplyOfferHisList;
        requestTag.action = page;
        request(entity, requestTag, onRequestListener);
    }

    OnRequestListener<OfferListEntity> onRequestListener = new OnRequestListener<OfferListEntity>() {
        @Override
        public OfferListEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, OfferListEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
            if (requestSucceedCount == 0){
                showExceptionView(R.mipmap.order_no, "网络问题,请点击重试", HttpRequest.FAIL_NET_FAULT);
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (requestSucceedCount == 0){
                showExceptionView(R.mipmap.order_no, arg + "", HttpRequest.FAIL_DATA_FAULT);//arg + ",请点击重试"
            }
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
        }

        @Override
        public void onStart(Object tag) {
            if (requestSucceedCount == 0){
                showProgressView();
            }
        }

        @Override
        public void onResponse(ResponseEntity<OfferListEntity> response, Object tag) {
            showMainView();
            requestSucceedCount ++;
            RequestTag requestTag = (RequestTag) tag;
            if (requestTag.action == 0) {
                list.clear();
            }
            OfferListEntity orderResponse = response.getResponseElement();
            List<OfferListEntity.ContentBean> content = orderResponse.getContent();
            tagPager.setLast(orderResponse.isLast());
            tagPager.setNumber(orderResponse.getNumber());
            tagPager.setSize(orderResponse.getSize());
            tagPager.setTotalElements(orderResponse.getTotalElements());
            for(int i=0;content!=null&&i<content.size();i++){
                OfferListEntity.ContentBean bean = content.get(i);
                for(int j=0;bean.getProductList()!=null&&j<bean.getProductList().size();j++){
                    bean.getProductList().get(j).setFather(bean);
                    if(j==0){
                        bean.getProductList().get(j).setHeader(true);
                    }
                    if(j==bean.getProductList().size()-1){
                        bean.getProductList().get(j).setFoot(true);
                    }
                }
                list.addAll(bean.getProductList());
            }

            adapter.notifyDataSetChanged();
            if(orderResponse.getNumber()==0){
                if(refreshFlag) {
                    mListView.setSelection(0);
                    refreshFlag=false;
                }
            }
            updateViewStatus(requestTag);
            if(list.size()==0){
                showExceptionView(R.mipmap.offer_no, "暂无抢单记录", HttpRequest.FAIL_DATA_EMPTY);
            }

        }
    };


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.baseback:
                // 返回上一页
                finish();
                break;
        }
    }
}
